//
//  PKSearchViewController.m
//  PianKe
//
//  Created by 王郑 on 16/2/27.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "PKSearchViewController.h"
#import "DDSoundModel.h"
#import "DDSoundTableViewCell.h"
#import "PKHomeDetailViewController.h"
// 间距的基本单位
#define kSMarge 5
#define kLMarge 10
@interface PKSearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>

@property (strong,nonatomic) NSArray  *dataList;

@property (strong,nonatomic) NSMutableArray  *searchList;

@property (strong,nonatomic) UITableView *tableview;

@property (nonatomic,strong) UISearchController *searchController;

@property (nonatomic,strong) UIView *viewshow;

@end

@implementation PKSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 不允许系统自动修改我们的frame
    self.automaticallyAdjustsScrollViewInsets = NO;
    
#pragma mark --- 自定义导航栏
    [self addBarView];
    
    // 搜索到的结果源 保存模型化后的model:
    _searchList = [NSMutableArray array];
    
    // 搜索到的数据源, 直接保存的时一个个字典 :
    self.dataList=[NSMutableArray arrayWithCapacity:100];
    
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStylePlain];
    self.tableview.dataSource =self;
    self.tableview.delegate = self;
    self.tableview.rowHeight = 120 * kHeightBase;
    self.tableview.scrollEnabled = NO;
    [self.view addSubview:self.tableview];
    
    
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    //设置开始搜索时背景显示与否
    _searchController.dimsBackgroundDuringPresentation = YES;
    //搜索时 设置显示导航栏与否
    _searchController.hidesNavigationBarDuringPresentation = YES;
    //搜索时背景变模糊
    _searchController.obscuresBackgroundDuringPresentation = NO;
    [self.searchController.searchBar sizeToFit];
    _searchController.searchBar.frame = CGRectMake(0, 0, kScreenWidth, 44*kHeightBase);
    
    // 把搜索控制器 设置为表的表头
    self.tableview.tableHeaderView = _searchController.searchBar;
    
    // 显示的view (放在tableView上面 , 搜索的时候把这个view移除) : 上面放写热门搜索按钮
    _viewshow = [[UIView alloc]initWithFrame:CGRectMake(0, (64+44)*kHeightBase, kScreenWidth, kScreenHeight-108*kHeightBase)];
    _viewshow.backgroundColor = [UIColor whiteColor];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenHeight/5, kScreenWidth, 5*kLMarge)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"热门搜索";
    [_viewshow addSubview:label];
    NSArray *array = @[@"贾樟柯",@"情人",@"艺术",@"阿乙",@"文学",@"社会"];
    for(int i = 0; i < 6; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(kScreenWidth/5*2, label.bottom  +i*5*kLMarge, kScreenWidth/5, 5*kLMarge) ;
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:20];
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [_viewshow addSubview:button];
        
    }
    
    [self.view addSubview:_viewshow];
    

}

#pragma mark --- 解析数据 :
-(void)setUpData
{
    NSURL *url = [NSURL URLWithString:@"http://static.owspace.com/?index.php?m=Home&c=Api&a=search&page_id=0&create_time=0" ];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    NSString *str = @"B709CBC5-0E2F-4C89-9E24-6AFBBA86C58C=device_id&iOS_version%3D1.0.0=version&key=%E8%B4%BE%E6%A8%9F%E6%9F%AF&p=1";
   
    // 根据搜索条里面的内容 , 拼接搜索的网址
    str = [str stringByReplacingOccurrencesOfString:@"%E8%B4%BE%E6%A8%9F%E6%9F%AF" withString:_searchController.searchBar.text];
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@"post"];
    [request setHTTPBody:data];
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        // 获取收货到的数据
        _dataList = dic[@"datas"][@"lists"];
        
        // 删除掉上一次搜索的数据
        if (self.searchList != nil) {
            [self.searchList removeAllObjects];
        }
        
        // 模型化
        for (NSDictionary *one in _dataList) {
            DDSoundModel *model = [[DDSoundModel alloc]init];
            [model setValuesForKeysWithDictionary:one];
            [_searchList addObject:model];
        }
        
        // 刷新tableview
        [_tableview reloadData];
    }];
    
}



#pragma mark ---  热门搜索 : 几个关键字的按钮点击的功能
-(void)button:(UIButton *)button
{
    
    self.searchController.searchBar.text = button.titleLabel.text;
    if (_searchController.searchBar.text.length != 0) {
        
        // 判断 : 我只要搜索条里面有东西 , 我就把showview移除掉,展示被他挡在下面的tableview
        [_viewshow removeFromSuperview];
        _tableview.scrollEnabled = YES;
        
    }
    _searchController.active =YES;
    
}

//
// 设置区域的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _searchList.count>0?_searchList.count:0;
}

//返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *flag=@"cellFlag";
    DDSoundTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
    if (cell==nil) {
        cell=[[DDSoundTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:flag];
    }
    if (_searchList.count != 0) {
        DDSoundModel *model = _searchList[indexPath.row];
        
        cell.model = model;
    }
    return cell;
}

// 更新搜索结果, 就是在输入东西的同时 , 一直在更新 :
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (_searchController.searchBar.text.length != 0) {
        
        [self setUpData];
        
    }
    NSString *searchString = [self.searchController.searchBar text];
    
    if (searchString.length == 0) {
        
        // 如果等于0,说明搜索条里面没有东西 , 我们把showview展示热门搜索的视图覆盖在tableview上面
        [self.view addSubview:_viewshow];
        // 并且把tableview禁止滑动
        self.tableview.scrollEnabled = NO;
    }else
    {
        [_viewshow removeFromSuperview];
        self.tableview.scrollEnabled = YES;
        
    }
    //刷新表格
    [self.tableview reloadData];
}



// 点击搜索结果的表上面的cell后跳转到具体的页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _searchController.active = NO;
    DDSoundModel *model = self.searchList[indexPath.row];
    PKHomeDetailViewController *sdVC = [[PKHomeDetailViewController alloc]init];
    sdVC.html5 = model.html5;
    sdVC.pageid = model.pageid;
    sdVC.category = model.category;
    sdVC.author = model.author;
    sdVC.titlename = model.title;
    sdVC.thumbnail = model.thumbnail;
    [self.navigationController pushViewController:sdVC animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 关闭搜索
    _searchController.active =NO;
}


- (void)addBarView
{
    // 创建自定义导航栏
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [self.view addSubview:headView];
    
    UIButton *leftBack = [UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBack.frame = CGRectMake(10*kWidthBase, 30*kHeightBase, 30*kWidthBase, 30*kHeightBase);
    [leftBack setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:(UIControlStateNormal)];
    [headView addSubview:leftBack];
    [leftBack addTarget:self action:@selector(backAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth - 200*kWidthBase)/2, leftBack.top, 200 * kWidthBase, leftBack.height)];
    titleLabel.text = @"搜      索";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:30];
    [headView addSubview:titleLabel];
    
    
}

- (void)backAction:(UIButton *)sender {
    
    _searchController.active = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
